package com.app.base.service.file.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.app.base.config.exception.SaaSException;
import com.app.base.service.file.service.FileService;
import com.app.base.utlis.result.Result;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Value("${file.upload.secretId}")
    private  String SECRET_ID;

    @Value("${file.upload.SecretKey}")
    private  String SECRET_KEY;

    @Value("${file.upload.region}")
    private  String REGION;

    @Value("${file.upload.bucket}")
    private  String BUCKET;

    @Value("${file.oss.endpoint}")
    private  String ENDPOINT;

    @Value("${file.oss.accessKeyId}")
    private  String ACCESS_KEY_ID;

    @Value("${file.oss.accessKeySecret}")
    private  String ACCESS_KEY_SECRET;

    @Value("${file.oss.bucketName}")
    private  String BUCKET_NAME;

    @Override
    public String uploadFileAvatar(MultipartFile file) {

        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try{
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();

            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename=uuid+filename;

            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            String dataPath = format.format(new Date());

            filename=dataPath+"/"+filename;

            ossClient.putObject(BUCKET_NAME, filename, inputStream);
            ossClient.shutdown();

            return "https://" +BUCKET_NAME+"."+ ENDPOINT +"/"+filename;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Result upload(MultipartFile file) {
        try{
            if (file.isEmpty()) {
                throw new SaaSException("文件未上传成功！请重新上传！");
            }
            COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
            Region region = new Region(REGION);
            ClientConfig clientConfig = new ClientConfig(region);
            clientConfig.setHttpProtocol(HttpProtocol.https);
            COSClient cosClient = new COSClient(cred, clientConfig);

            String bucketName = BUCKET;
            String key = file.getOriginalFilename();

            assert key != null;
            String extension = key.substring(key.lastIndexOf("."));
            String notExtension = extension.substring(1);
            String filePath = notExtension+"/"+ UUID.randomUUID() + extension;

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, file.getInputStream(),new ObjectMetadata());
            cosClient.putObject(putObjectRequest);

            HashMap<String, Object> map = new HashMap<>();
            map.put("size",file.getSize());
            map.put("url","https://qwer123we-1308973984.cos.ap-nanjing.myqcloud.com/"+filePath);
            map.put("attachmentType",extension);
            map.put("fileName",key);
            return Result.ok(map);
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }
}
